'use strict';

function isObject(o){
    return Object.prototype.toString.call(o) === '[object Object]'
}

function spinnerStart(message, spinnerString = '|/-\\'){
    const Spinner = require("cli-spinner").Spinner
    const cliSpinner = new Spinner(message + ' %s')
    cliSpinner.setSpinnerString(spinnerString)
    cliSpinner.start()
    return cliSpinner
}

function sleep (timeout = 1000){
    return new Promise(resolve => setTimeout(resolve, timeout))
}

/**
 * mac 直接 node ['-e', xxx]
 * win 通过 cmd  ['/c', 'node', 'e', xxx]
 * @param {*} command  node || cmd
 * @param {*} args ['-e', xxx] || ['/c', 'node', 'e', xxx]
 * @param {*} options  spawn 配置
 * @returns 
 */
function execCommand(command, args, options){
    const win32 = process.platform === 'win32'
    const cmd = win32 ? 'cmd' : command
    const cmdArgs = win32 ? ['/c'].concat(command, args) : args
    return require('child_process').spawn(cmd, cmdArgs, options || {})
}

function execCommandAsync(command, args, options){
    return new Promise((resolve, reject) => {
        const p = execCommand(command, args, options)
        p.on('error', e => {
            reject(e)
        })
        p.on('exit', _ => {
            resolve(0)
        })
    })
}
    


module.exports = {
    isObject,
    spinnerStart,
    sleep,
    execCommand,
    execCommandAsync
};